<template>
  <div class="app-container">
    <el-tabs v-model="activeTabName" type="border-card" @tab-click="handleTabClick">
      <el-tab-pane name="listTab">
        <span slot="label"><i class="el-icon-money" />节假日信息</span>
        <div class="filter-container query">
          <el-select v-model="listQuery.dayType" :filterable="true" placeholder="日期类型" class="filter-item" style="width: 200px;" clearable @keyup.enter.native="handleFilter">
            <el-option
              v-for="item in dayTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-date-picker v-model="listQuery.dayStr" type="daterange" value-format="yyyyMMdd" placeholder="日期" class="filter-item" style="width: 300px;" @keyup.enter.native="handleFilter" />
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleFilter">
            搜索
          </el-button>
          <el-button type="info" icon="el-icon-refresh" size="small" @click="handleReset">
            重置
          </el-button>
          <el-button type="success" icon="el-icon-circle-plus-outline" size="small" @click="handleCreate">
            新增
          </el-button>
          <el-button type="warning" icon="el-icon-upload2" size="small" @click="handleUpload">
            导入
          </el-button>
          <el-button type="success" icon="el-icon-upload2" size="small" @click="handleGenerate">
            生成周末
          </el-button>
          <el-button :loading="fileDownloading" type="danger" icon="el-icon-download" size="small" @click="handleDownload">
            导出
          </el-button>
        </div>

        <el-table
          :loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;height: 100%;"
          size="small"
          @sort-change="sortChange"
        >
          <el-table-column label="操作" header-align="center" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="{row}">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">
                编辑
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="日期" prop="dayStr" sortable="custom" width="200" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.dayStr | formateStrDate8() }}</span>
            </template>
          </el-table-column>
          <el-table-column label="日期类型" prop="dayType" :formatter="formatter" sortable="custom" width="200" header-align="center" align="center" />
          <el-table-column label="节日描述" prop="dayDesc" width="350" header-align="center" align="left">
            <template slot-scope="scope">
              <span>{{ scope.row.dayDesc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createAt" sortable="custom" width="200" header-align="center" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.createAt }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageNoSize" size="small" @pagination="getList" />

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="500px" :close-on-click-modal="false" :close-on-press-escape="false" center>
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" class="form-center">
            <el-form-item label="日期" prop="dayStr">
              <el-date-picker v-model="temp.dayStr" type="date" value-format="yyyyMMdd" :disabled="dialogStatus!=='create'" />
            </el-form-item>
            <el-form-item label="日期类型" prop="dayType">
              <el-select v-model="temp.dayType">
                <el-option
                  v-for="item in dayTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="节日描述" prop="dayDesc">
              <el-input v-model="temp.dayDesc" autosize type="textarea" :rows="3" maxlength="128" show-word-limit />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              取消
            </el-button>
            <el-button :loading="ajaxLoading" type="primary" @click="dialogStatus==='create'?createData():updateData()">
              确认
            </el-button>
          </div>
        </el-dialog>

        <el-dialog
          title="生成指定年份周末信息"
          :visible.sync="dialogWeekendFormVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          width="400px"
          center
        >
          <el-form
            ref="dataWeekendForm"
            :rules="rules"
            :model="weekendTemp"
            label-position="right"
            label-width="100px"
            class="form-center"
          >
            <el-form-item label="开始年份" prop="startYear">
              <el-date-picker v-model="weekendTemp.startYear" type="year" value-format="yyyy" />
            </el-form-item>
            <el-form-item label="结束年份" prop="endYear">
              <el-date-picker v-model="weekendTemp.endYear" type="year" value-format="yyyy" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogWeekendFormVisible = false">
              取消
            </el-button>
            <el-button :loading="ajaxLoading" type="primary" @click="doGenerateWeekends()">
              确认
            </el-button>
          </div>
        </el-dialog>

        <el-dialog
          title="Excel导入节日信息"
          :visible.sync="uploadExcelDialogVisible"
          :destroy-on-close="true"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          center
        >
          <div class="app-container">
            <el-upload
              ref="upload"
              action="customized"
              :limit="1"
              accept=".xls,.xlsx"
              :http-request="handleExcelUpload"
              :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
              <el-button :loading="fileUploading" style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              <el-button :loading="fileDownloading" style="margin-left: 10px;" size="small" type="info" @click="handleDownloadTemplate">下载模板</el-button>
              <div slot="tip" class="el-upload__tip">只允许上传.xls、.xlsx文件</div>
            </el-upload>
          </div>
        </el-dialog>
      </el-tab-pane>

      <el-tab-pane name="calendarTab">
        <span slot="label"><i class="el-icon-date" />日历</span>
        <el-calendar v-model="calendarValue">
          <template
            slot="dateCell"
            slot-scope="{date, data}"
          >
            <p v-if="showCalendar" :class="data.isSelected ? 'is-selected' : ''">
              {{ trimDate(data.day) }}
              <svg-icon :icon-class="getDayType(data.day)" />
            </p>
            <span class="day-desc">{{ getDayDesc(data.day) }}</span>
          </template>
        </el-calendar>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { fetchList, createHolidayInfo, updateHolidayInfo, deleteHolidayInfo, importHolidayInfo, exportHolidayInfo, exportHolidayInfoTemplate, generateWeekends, getMonthList } from '@/api/base/holiday'
import Pagination from '@/components/Pagination'
import { saveRespExcel } from '@/utils'
import { setOptionData, valueFormate } from '@/utils/dict'

export default {
  name: 'HolidayInfo',
  components: { Pagination },
  data() {
    return {
      activeTabName: 'listTab',
      dayTypeOptions: [],
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNo: 1,
        pageSize: 20,
        dayStr: [],
        dayType: '',
        sortField: undefined,
        sortOrder: undefined
      },
      temp: {
        dayStr: '',
        dayType: '',
        dayDesc: ''
      },
      dialogFormVisible: false,
      dialogHolidayInfoFormVisible: false,
      uploadExcelDialogVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新节日描述信息',
        create: '新增节日描述信息'
      },
      rules: {
        dayStr: [{ required: true, message: '日期不能为空', trigger: 'change' },
          { max: 8, message: '日期长度不能大于8个字符', trigger: 'change' }],
        dayType: [{ required: true, message: '日期类型不能为空', trigger: 'change' }],
        dayDesc: [{ max: 128, message: '节日描述长度不能大于128个字符', trigger: 'change' }],
        startYear: [{ required: true, message: '开始年份不能为空', trigger: 'change' }],
        endYear: [{ required: true, message: '结束年份不能为空', trigger: 'change' }]
      },
      fileDownloading: false,
      fileUploading: false,
      ajaxLoading: false,
      dialogWeekendFormVisible: false,
      weekendTemp: {
        startYear: '',
        endYear: ''
      },
      calendarValue: new Date(),
      holidayMonthArray: [],
      showCalendar: false
    }
  },
  watch: {
    calendarValue: {
      immediate: true,
      handler(value) {
        const y = value.getFullYear()
        const m = value.getMonth() + 1
        const month = y + '' + (m > 9 ? m : ('0' + m))
        this.showCalendar = false
        getMonthList(month).then(response => {
          if (response.data) {
            this.holidayMonthArray = response.data
            this.showCalendar = true
          } else {
            this.holidayMonthArray = []
          }
        })
      }
    }
  },
  created() {
    this.getList()
    // 加载下拉数据
    const optionsMap = new Map()
    optionsMap.set('BASE_DAY_TYPE', this.dayTypeOptions)
    setOptionData(optionsMap)
  },
  methods: {
    getDayDesc(dayStr) {
      const day = dayStr.replace(/-/g, '')
      let result = ''
      if (this.holidayMonthArray && this.holidayMonthArray.length > 0) {
        for (const holiday of this.holidayMonthArray) {
          if (holiday.dayStr !== day) {
            continue
          }
          result = holiday.dayDesc
          break
        }
      }
      return result
    },
    getDayType(dayStr) {
      const day = dayStr.replace(/-/g, '')
      let result = ''
      if (this.holidayMonthArray && this.holidayMonthArray.length > 0) {
        for (const holiday of this.holidayMonthArray) {
          if (holiday.dayStr !== day) {
            continue
          } else if (holiday.dayType === '1') {
            result = 'holiday2'
            break
          } else if (holiday.dayType === '2') {
            result = 'workday'
            break
          } else if (holiday.dayType === '3') {
            result = 'weekend'
            break
          }
        }
      }
      return result
    },
    trimDate(dayStr) {
      return dayStr.substring(8, 10)
    },
    handleTabClick() {
      switch (this.activeTabName) {
        case 'calendarTab':
          this.loadMonthHolidayData()
          break
      }
    },
    loadMonthHolidayData() {
      if (this.calendarValue) {
        const y = this.calendarValue.getFullYear()
        const m = this.calendarValue.getMonth() + 1
        const month = y + '' + (m > 9 ? m : ('0' + m))
        getMonthList(month).then(response => {
          if (response.data) {
            this.holidayMonthArray = response.data
            this.showCalendar = true
          } else {
            this.holidayMonthArray = []
          }
        })
      }
    },
    handleCalendarChange(value) {
      this.loadMonthHolidayData()
    },
    formatter(row, column, cellValue, index) {
      return valueFormate(this, column.property, cellValue)
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }, response => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleReset() {
      this.listQuery = {
        dayStr: [],
        dayType: ''
      }
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortByField(prop, order)
    },
    sortByField(prop, order) {
      if (order === 'ascending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'asc'
      } else if (order === 'descending') {
        this.listQuery.sortField = prop
        this.listQuery.sortOrder = 'desc'
      } else {
        this.listQuery.sortField = undefined
        this.listQuery.sortOrder = undefined
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        dayStr: '',
        dayType: '',
        dayDesc: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createHolidayInfo(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$message({
              message: '节日描述信息保存成功！',
              type: 'success'
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateHolidayInfo(tempData).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$message({
              message: '节日描述信息更新成功！',
              type: 'success'
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$msgbox({
        type: 'warning',
        title: '确认信息',
        message: '节日描述信息删除后将不可恢复，确认要删除该信息？',
        showCancelButton: true,
        showClose: false,
        closeOnPressEscape: false,
        closeOnClickModal: false,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            deleteHolidayInfo(row.id).then((response) => {
              this.getList()
              this.$message({
                message: '节日描述信息删除处理成功！',
                type: 'success'
              })
              done()
              instance.confirmButtonLoading = false
            }, (response) => {
              done()
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).catch(() => {})
    },
    handleUpload() {
      this.uploadExcelDialogVisible = true
    },
    handleExcelUpload(file) {
      if (!file || !file.file) {
        return function() {
          Promise.resolve(file)
        }
      }
      this.fileUploading = true
      importHolidayInfo(file).then(response => {
        this.getList()
        this.$message({
          message: '数据文件上传导入处理成功！',
          type: 'success'
        })
        this.fileUploading = false
        this.uploadExcelDialogVisible = false
      }, response => {
        this.fileUploading = false
      })
    },
    handleDownload() {
      this.fileDownloading = true
      exportHolidayInfo(this.listQuery).then(response => {
        saveRespExcel(response)
        this.fileDownloading = false
      }, (response) => {
        this.fileDownloading = false
      })
    },
    handleDownloadTemplate() {
      this.fileDownloading = true
      exportHolidayInfoTemplate().then(response => {
        saveRespExcel(response)
        this.fileDownloading = false
      }, (response) => {
        this.fileDownloading = false
      })
    },
    handleGenerate() {
      this.weekendTemp = {
        startYear: '',
        endYear: ''
      }
      this.dialogWeekendFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataWeekendForm'].clearValidate()
      })
    },
    doGenerateWeekends() {
      this.$refs['dataWeekendForm'].validate((valid) => {
        if (valid) {
          this.ajaxLoading = true
          generateWeekends(this.weekendTemp.startYear, this.weekendTemp.endYear).then(() => {
            this.getList()
            this.ajaxLoading = false
            this.dialogFormVisible = false
            this.$message({
              message: '周末信息新增成功！',
              type: 'success'
            })
          }, () => {
            this.ajaxLoading = false
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .is-selected {
    color: #1989FA;
  }
  .day-desc {
    color:brown;
  }
</style>
